﻿using LdtDataEngin.ModuleDetail.CaseElmentOpt;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LdtDataEngin.ModuleDetail.BaseModule.Optimization
{
    public class SgingOPtimizationBase : OptimizationBase
    {
        public int IsStage = 0;

        public Xmllable xmlConfig { get; set; }
        /// <summary>
        /// 相同合并方式
        /// </summary>
        public MergeModel mergeModel { get; set; }

        public List<Sourcedatadefine> Sourcedatadefine { get; set; }
        /// <summary>
        /// 优选级比较
        /// </summary>
        /// <param name="dataModelAsis">分析节点</param>
        /// <param name="dataModelOP">上次结果节点</param>
        /// <param name="opsum">优选序位</param>
        /// <param name="assum">分析序位</param>
        /// <param name="xmllableConfig">配置信息</param>
        /// <param name="soursnameopid"></param>
        /// <param name="soursnameasisid"></param>
        public void SgingBase(DataModel dataModelAsis, DataModel dataModelOP, int opsum, int assum, Xmllable xmllableConfig, string soursnameopid, string soursnameasisid)
        {
            string sourCode = dataModelAsis.sourceData.sourceList.FirstOrDefault(a=>a.IsCheck=="1").SourceCode;
            if (Sourcedatadefine!=null && Sourcedatadefine.Count>0)
            {
                if (Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == sourCode.ToLower())!=null)
                {
                    assum = ListByCount(xmllableConfig.Priority.Split('>').ToList(), Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == sourCode.ToLower()).id.ToString());
                }
               
                
            }
            LdtJudge.DataEngine.Model.XMLConfigModel.DataStores.Source sourceNodeOP = new Source();
            if (dataModelOP.sourceData != null)
            {
                sourceNodeOP = dataModelOP.sourceData.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == sourCode.ToLower());
            }

            if (sourceNodeOP != null && dataModelOP.sourceData != null)
            {
                sourceNodeOP = dataModelAsis.sourceData.sourceList.FirstOrDefault(a=>a.IsCheck=="1");
            }
            else
            {
                Source sourceopdata = dataModelAsis.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1");
                sourceopdata.IsCheck = "0";
                if (dataModelOP.sourceData == null)
                {
                    dataModelOP.sourceData = new SourceData();
                    dataModelOP.AttributesList = new List<AttributeInfo>();
                    dataModelOP.sourceData.sourceList = new List<Source>();
                }
                dataModelOP.sourceData.sourceList.Add(sourceopdata);
            }
            var sourceIdList = dataModelOP.sourceData.sourceList.Where(x=>x.SourceCode.ToLower()== "evidencedata")
                                          .Select(x => x.SourceID).ToList().Distinct().ToList();
            if (sourceIdList != null && sourceIdList.Any())
            {
                foreach (var item in sourceIdList)
                {
                    if (dataModelOP.sourceData.sourceList.Where(x => x.SourceID == item).Count() > 1 && !string.IsNullOrWhiteSpace(item))
                    {
                        List<Source> delSource = new List<Source>();
                        delSource.AddRange(dataModelOP.sourceData.sourceList.Where(x => x.SourceID == item).Skip(1));
                        if(delSource.Any())
                        {
                            foreach (var delItem in delSource)
                            {
                                dataModelOP.sourceData.sourceList.Remove(delItem);
                            }
                        }
                    }
                }
            }

            if (assum <= opsum)
            {
                List<Source> addSources = new List<Source>();
                foreach (Source sourceNode in dataModelOP.sourceData.sourceList)
                {
                    sourceNode.AnalysisStatus = "1";
                    if (IsStage == 1)
                    {
                        if (sourceNode.SourceCode.ToLower() == sourCode.ToLower())
                        {
                            sourceNode.IsCheck = "1";
                        }
                        else
                        {
                            sourceNode.IsCheck = "0";
                        }
                    }
                    else
                    {
                        if (sourceNode.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower())
                        {
                            sourceNode.IsCheck = "1";
                            //TODO:证据与事实要素关系建立
                            if (sourceNode.SourceCode.ToLower() == "evidencedata")
                            {
                                Source sameEvidSource = null;
                                if (sourceNodeOP!=null && !string.IsNullOrWhiteSpace(sourceNodeOP.SourceID))
                                {


                                    sameEvidSource = dataModelOP.sourceData.sourceList.FirstOrDefault(x => x.SourceID == sourceNodeOP.SourceID);
                                    if (sameEvidSource == null)
                                    {
                                        sourceNode.IsCheck = "0";
                                        sourceNodeOP.IsCheck = "1";
                                        sourceNodeOP.AnalysisStatus = "1";
                                        addSources.Add(sourceNodeOP);
                                    }
                                    else if (sourceNode.SourceID == sourceNodeOP.SourceID)
                                    {
                                        sourceNode.SourceNodeId = sourceNodeOP.SourceNodeId;
                                    }
                                }
                            }
                        }
                        else
                        {
                            sourceNode.IsCheck = "0";
                        }
                    }
                }
                if (addSources != null && addSources.Any())
                {
                    foreach (var item in addSources)
                    {
                        dataModelOP.sourceData.sourceList.Add(item);
                    }
                }
            }
            if (dataModelAsis.AttributesList!=null)
            {
                //循环比较属性信息
                foreach (AttributeInfo attritem in dataModelAsis.AttributesList)
                {
                    bool determine = true;
                    AttributeInfo attributeop = dataModelOP.AttributesList.FirstOrDefault(a => a.Name == attritem.Name && a.Name != "id");
                    if (attributeop == null)
                    {
                        AttributeInfo attributeTmp = new AttributeInfo();
                        attributeTmp.Name = attritem.Name;
                        attributeTmp.DictionariesCode = attritem.DictionariesCode;
                        attributeTmp.Priority = attritem.Priority;
                        attributeTmp.sourceList = attritem.sourceList;
                        dataModelOP.AttributesList.Add(attributeTmp);
                    }
                    else
                    {
                        string srcode = dataContext.DataLayerAns.SourceCode.ToLower();
                        if (IsStage == 1)
                        {
                            srcode = sourCode.ToLower();
                        }
                        if (attributeop.sourceList.FirstOrDefault(a => a.SourceCode != null && a.SourceCode.ToLower() == srcode) == null)
                        {
                            Source attsoucremodel = attritem.sourceList.FirstOrDefault(a=>a.IsCheck=="1");
                            attsoucremodel.IsCheck = "0";
                            attributeop.sourceList.Add(attsoucremodel);
                        }
                        if (xmllableConfig.ElementList != null)
                        {
                            if (Sourcedatadefine != null && Sourcedatadefine.Count > 0)
                            {
                                string opname = attributeop.sourceList.FirstOrDefault(a => a.IsCheck == "1").SourceCode;

                                //opsum = ListByCount(xmllableConfig.Priority.Split('>').ToList(), Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == opname.ToLower()).id.ToString());
                                try
                                {
                                    soursnameopid = Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == opname.ToLower()).id.ToString();
                                }
                                catch (Exception ex)
                                {

                                    dataContext.InteractiveShow.LogShow("数据源不存在"); ;
                                }
                                
                            }
                            Element element = xmllableConfig.ElementList.FirstOrDefault(a => a.Name == attritem.Name);
                            if (element!=null && string.IsNullOrEmpty(element?.Priority) && !string.IsNullOrWhiteSpace(xmllableConfig?.Priority))
                            {
                                element.Priority = xmllableConfig.Priority;
                            }
                            if (element != null && !string.IsNullOrEmpty(element.Priority))
                            {
                                if (element.ConditionList.Count > 0)
                                {
                                    try
                                    {
                                        //determine = ConditionDetermine(element.ConditionList);
                                    }
                                    catch (Exception ef)
                                    {
                                        dataContext.InteractiveShow.LogShow("当前数据项条件解析错误，配置信息：" + JsonConvert.SerializeObject(ef.ToString()));
                                        dataContext.InteractiveShow.LogShow("当前数据项条件解析错误，错误信息：" + ef.ToString());
                                    }
                                }

                                opsum = ListByCount(element.Priority.Split('>').ToList(), soursnameopid);
                                assum = ListByCount(element.Priority.Split('>').ToList(), soursnameasisid);
                                if (assum<=opsum)
                                {
                                    for (int i = 0; i < attributeop.sourceList.Count; i++)
                                    {
                                        if (attributeop.sourceList[i].SourceCode!=null)
                                        {
                                            if (attributeop.sourceList[i].SourceCode.ToLower() == sourCode.ToLower())
                                            {
                                                attributeop.sourceList[i].IsCheck = "1";
                                            }
                                            else
                                            {
                                                attributeop.sourceList[i].IsCheck = "0";
                                            }
                                        }
                                        
                                    }
                                }
                            }
                        }
                        if (!determine)
                        {
                            return;
                        }
                        try
                        {
                            if (attributeop.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == sourCode.ToLower()) != null && IsStage == 1)
                            {
                                if (!string.IsNullOrEmpty(attritem.sourceList[0].SaveValue))
                                {
                                    attributeop.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == sourCode.ToLower()).SaveValue = attritem.sourceList[0].SaveValue;
                                }
                                
                                continue;
                            }
                            else if (attributeop.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()) != null)
                            {
                                if (!string.IsNullOrEmpty(attritem.sourceList[0].SaveValue))
                                {
                                    attributeop.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).SaveValue = attritem.sourceList[0].SaveValue;
                                }
                                    
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            dataContext.InteractiveShow.LogShow("数据源不存在");
                        }
                       
                        if (assum < opsum)
                        {
                            foreach (LdtJudge.DataEngine.Model.XMLConfigModel.DataStores.Source attsource in attributeop.sourceList)
                            {
                                attsource.AnalysisStatus = "1";
                               
                                if (IsStage == 1)
                                {
                                   
                                    if (attsource.SourceCode.ToLower() == sourCode.ToLower())
                                    {
                                        attsource.IsCheck = "1";
                                    }
                                    else
                                    {
                                        attsource.IsCheck = "0";
                                    }
                                }
                                else
                                {
                                    if (attsource.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower())
                                    {
                                        attsource.IsCheck = "1";
                                    }
                                    else
                                    {
                                        attsource.IsCheck = "0";
                                    }
                                }
                            }
                        }
                        else if (assum == opsum)
                        {
                            try
                            {
                                //处理问题@@@##
                                if (attritem.sourceList.FirstOrDefault(a => a.IsCheck == "1") == null)
                                {
                                    if (attritem.sourceList.Count > 0)
                                    {
                                        attritem.sourceList[0].IsCheck = "1";
                                    }
                                }

                                if (attributeop.sourceList.FirstOrDefault(a => a.IsCheck == "1") == null)
                                {
                                    if (attributeop.sourceList.Count > 0)
                                    {
                                        attributeop.sourceList[0].IsCheck = "1";
                                    }
                                }

                                bool Isreplace = true;
                                if (mergeModel != null && mergeModel.xmlMultiple != null && !string.IsNullOrEmpty(mergeModel.AsisModle) && !string.IsNullOrEmpty(mergeModel.OPModle) && mergeModel.xmlMultiple.XmllableList != null)
                                {
                                    var mlabel = mergeModel.xmlMultiple.XmllableList.FirstOrDefault(a => a.Xmlpath == xmllableConfig.Xmlpath);
                                    if (mlabel != null)
                                    {
                                        if (mlabel.ElementList != null && mlabel.ElementList.Count > 0)
                                        {
                                            var elementcon = mlabel.ElementList.FirstOrDefault(a => a.Name == attritem.Name);
                                            if (elementcon != null)
                                            {
                                                string prior = elementcon.Priority;
                                                if (mergeModel.OPModle.ToLower() == prior)
                                                {
                                                    Isreplace = false;
                                                }
                                            }
                                        }
                                    }
                                }
                                if (Isreplace)
                                {
                                    LdtJudge.DataEngine.Model.XMLConfigModel.DataStores.Source sourceasis = attritem.sourceList.FirstOrDefault(a => a.IsCheck == "1");
                                    LdtJudge.DataEngine.Model.XMLConfigModel.DataStores.Source sourceop = attributeop.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == sourceasis.SourceCode.ToLower());
                                    if (attributeop.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == srcode.ToLower()) == null)
                                    {
                                        if (attributeop.sourceList.FirstOrDefault(a => a.IsCheck == "1") == null)
                                        {
                                            if (attributeop.sourceList.Count > 0)
                                            {
                                                attributeop.sourceList[0].IsCheck = "1";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        attributeop.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == srcode.ToLower()).SaveValue = sourceasis.SaveValue;
                                        if (attributeop.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == srcode.ToLower()).IsCheck == "1")
                                        {
                                            attributeop.sourceList.Remove(sourceop);
                                            attributeop.sourceList.Add(sourceasis);
                                        }
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        if (assum <= opsum && IsStage != 1)
                        {
                            if (attributeop.sourceList.FirstOrDefault(a => a.IsCheck == "1") == null)
                            {
                                foreach (Source sourceNode in attributeop.sourceList)
                                {
                                    sourceNode.AnalysisStatus = "1";
                                    if (sourceNode.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower())
                                    {
                                        sourceNode.IsCheck = "1";
                                    }
                                    else
                                    {
                                        sourceNode.IsCheck = "0";
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
